<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Task extends AdminController
{
    public $_validation = null;

    function __construct()
    {
        parent::__construct();
        $this->load->model('MTask');
        $this->load->model('MShop');
        $this->load->model('MAdminGroup');
        $this->load->model('MAdmin');
        $allShops = $this->MShop->getAllShops();
        $allDistribution = $this->MAdmin->getAllDistribution();
        $allGroups = $this->MAdminGroup->getAllGroupsByType(1);

        $this->_validation = Array(
            array('field' => 'shop_id', 'label' => '账户', 'rules' => 'required|integer|max_length[11]')
        , array('field' => 'creator_id', 'label' => '创建者', 'rules' => 'required|max_length[11]')
        , array('field' => 'task_contact_id', 'label' => '组员', 'rules' => 'required|integer|max_length[11]')
        , array('field' => 'price', 'label' => '价格', 'rules' => 'required')
        , array('field' => 'group_id', 'label' => '所属管理组', 'rules' => 'required|integer')
        , array('field' => 'product_name', 'label' => '商品名称', 'rules' => 'trim|required|max_length[255]')
        , array('field' => 'related_shop', 'label' => '任务其他店铺', 'rules' => '')
        , array('field' => 'profit_rate', 'label' => '利润率', 'rules' => '')
        , array('field' => 'search_key', 'label' => '搜索关键词', 'rules' => 'trim|required|max_length[255]')
        , array('field' => 'amazon_order', 'label' => 'amazon搜索关键词的排名', 'rules' => 'trim|required|max_length[255]')
        , array('field' => 'asin', 'label' => '商品ASIN', 'rules' => 'trim|required|exact_length[10]')
        , array('field' => 'price', 'label' => '商品价格', 'rules' => 'numeric')
        , array('field' => 'country', 'label' => '国家', 'rules' => 'trim|required|max_length[2]')
        , array('field' => 'link', 'label' => '商品链接', 'rules' => 'trim|max_length[1024]')
        , array('field' => 'image', 'label' => '商品图片', 'rules' => 'upload[upload_path=product,encrypt_name=true]')
        , array('field' => 'sale_need_num', 'label' => '要求销量总数', 'rules' => 'required|integer|max_length[5]')
        , array('field' => 'comment_need_num', 'label' => '要求测评总数', 'rules' => 'required|integer|max_length[5]')
        , array('field' => 'requirement_desc', 'label' => '任务要求具体说明', 'rules' => 'max_length[255]')
        , array('field' => 'status', 'label' => '任务状态', 'rules' => 'integer')
        , array('field' => 'is_urgent', 'label' => '是否加急', 'rules' => 'integer')
        , array('field' => 'remark', 'label' => '备注', 'rules' => 'max_length[255]')
        , array('field' => 'update_time', 'label' => '更新时间', 'rules' => '')
        );
        $this->assign('currentRoleId', $this->_user->role_id);
        $this->assign('allShops', $allShops);
        $this->assign('allDistribution', $allDistribution);
        $this->assign('allGroups', $allGroups);
    }

    public function index()
    {
        //$this->output->enable_profiler(TRUE);
        $allShop = $this->MShop->getAllShop();
        $this->load->library('FormFilter');
        $this->load->helper('formfilter');
        $this->formfilter->addFilter('t.product_name', 'like');
        $this->formfilter->addFilter('t.id', 'where');
        $this->formfilter->addFilter('t.asin', 'where');
        $this->formfilter->addFilter('t.shop_id', 'where');
        $this->formfilter->addFilter('t.group_id', 'where');
        $this->formfilter->addFilter('t.task_contact_id', 'where');
        $this->formfilter->addFilter('t.status', 'where');
        $this->formfilter->addFilter('t.is_urgent', 'where');
        $this->formfilter->addFilter('t.country', 'where');

        if ($begintime = filterValue('task_create_time_begin')) {
            $this->formfilter->addFilter('task_create_time_begin', 'where', array('t.create_time >= ', strtotime($begintime . ' 00:00:00')));
        }
        if ($endtime = filterValue('task_create_time_end')) {
            $this->formfilter->addFilter('task_create_time_end', 'where', array('t.create_time <= ', strtotime($endtime . ' 23:59:59')));
        }

        $number_perpage = filterValue('task_number_perpage');
        $order_type = filterValue('task_order_type');

        $total_number = $this->MTask->getCount();
        $limit = $this->pagination($total_number, '', $number_perpage);
        $list = $this->MTask->getList($limit, $order_type);

        $this->assign('list', $list);
        $this->assign('allShop', $allShop);
        $this->assign('total_number', $total_number);
        $this->layout();
    }

    public function add()
    {
        $allShops = $this->MShop->getAllShops();
        $allDistribution = $this->MAdmin->getAllDistribution();
        $obj = $this->MTask->createVo();

        $obj->task_contact_id = $this->_user->id;
        $obj->creator_id = $this->_user->id;
        $this->load->library('form_validation');
        $this->form_validation->set_rules($this->_validation);

        if ($this->form_validation->run() == TRUE) {
            $this->load->helper('populate');
            $newObj = populate((Object)((Array)$obj), $this->form_validation->post());

            //检查是否已有相同的asin和shop_id
            $oldTask = $this->MTask->getOne(array('asin'=>$newObj->asin,'shop_id'=>$newObj->shop_id));
            if($oldTask){
                errorAndRedirect('已经存在同一店铺中相同asin的记录，请检查！');
            }

            if ($this->MTask->add($newObj)) {
                successAndRedirect('添加任务成功');
            } else {
                errorAndRedirect(l('data_fail'));
            }
        }
        $this->assign('obj', $obj);
        $this->assign('allShops', $allShops);
        $this->assign('allDistribution', $allDistribution);
        $this->layout();
    }

    function edit($id)
    {
        $allShops = $this->MShop->getAllShops();
        $allDistribution = $this->MAdmin->getAllDistribution();

        if (!is_numeric($id)) {
            show_error(l('id_not_null'));
        }
        $obj = $this->MTask->getOne(Array('id' => $id));
        if (!$obj) {
            errorAndRedirect('未找到定义！');
        }
        $this->editObj = $obj;
        $this->load->library('form_validation');
        $this->form_validation->set_rules($this->_validation);
        if ($this->form_validation->run() == TRUE) {
            $data = $this->input->post();

            if ($data['comment_need_num'] < $obj->comment_applied_num){
                errorAndRedirect('任务测评需求数量不可低于已接测评数量！');
            }
            if ($data['sale_need_num'] < $obj->sale_applied_num){
                errorAndRedirect('任务销量需求数量不可低于已接销量数量！');
            }

            $this->load->helper('populate');
            $newObj = populate((Object)((Array)$obj), $this->form_validation->post());

            //检查是否已有相同的asin和shop_id
            if ($obj->asin !== $newObj->asin || $obj->shop_id !== $newObj->shop_id){
                $oldTask = $this->MTask->getOne(array('asin'=>$newObj->asin,'shop_id'=>$newObj->shop_id));
                if($oldTask){
                    errorAndRedirect('已经存在同一店铺中相同asin的记录，请检查！');
                }
            }

            if ($this->MTask->update($newObj)) {

                successAndRedirect(l('edit_success'));
            } else {
                errorAndRedirect(l('data_fail'));
            }
        }
        $this->assign('obj', $obj);
        $this->assign('allShops', $allShops);
        $this->assign('allDistribution', $allDistribution);
        $this->layout();
    }


    function view($id)
    {
        if (!is_numeric($id)) {
            show_error(l('id_not_null'));
        }
        $this->load->model('MTaskApplyNum');
        $obj = $this->MTask->getOne(Array('id' => $id));
        $apply = $this->MTaskApplyNum->getOne(['operator_id' => $this->_user->id, 'task_id' => $id]);
        if (!$obj) {
            errorAndRedirect('未找到定义！');
        }
        //该任务的所有操作记录
        $this->load->model('MTaskRecords');
        $allOperatesOfTaskId = $this->MTaskRecords->getAll(array('task_id =' => $id));
        $distinctOrderNoOperates = $this->MTaskRecords->getDistinctOrderNoOperates($id,$this->_user->id);

        $allReviewsAdmin = $this->MAdmin->getAllReviewsAdmin();//所有测评人
        if ($apply && (int)$distinctOrderNoOperates->operate_numbers < (int)($apply->apply_sale_num + $apply->apply_comment_num)) {
            $obj->is_apply = true;
        }else{
            $obj->is_apply = false;
        }

        $this->assign('obj', $obj);
        $this->assign('allOperatesOfTaskId', $allOperatesOfTaskId);
        $this->assign('allReviewsAdmin', $allReviewsAdmin);
        $this->layout('view.tpl');
    }

    function delete($id, $update_time)
    {
        if (!is_numeric($id) || !is_numeric($update_time)) {
            show_error(l('id_not_null'));
        }
        if (!$this->MTask->delete($id, $update_time)) {
            errorAndRedirect(l('data_fail'));
        }
        successAndRedirect(l('delete_success'));
    }

    function ajaxTaskApply()
    {
        $this->load->model('MTaskApplyNum');
        $this->load->helper('populate');
        $data = $this->input->post();
        $obj = $this->MTask->getOne(Array('id' => $data['task_id']));
        if (!$obj) {
            exit(json_encode([
                'success' => 0,
                'msg' => '无效的任务'
            ]));
        }
        $this->db->trans_start();
        $his = $this->MTaskApplyNum->getOne([
            'task_id' => $data['task_id'],
            'operator_id' => $this->_user->id
        ]);
        if ($data['apply_type'] == 'sale') {
            $obj->sale_applied_num += $data['apply_num'];
            if ($obj->sale_applied_num > $obj->sale_need_num) {
                exit(json_encode([
                    'success' => 0,
                    'msg' => '超出最大可接销量数目，请刷新后重试'
                ]));
            }
            if ($his) {
                $his->apply_sale_num += $data['apply_num'];
                if (!$this->MTaskApplyNum->update($his)) {
                    $this->db->_trans_status = FALSE;
                }
            } else {
                $add_obj = $this->MTaskApplyNum->createVo();
                $add_obj->apply_sale_num = $data['apply_num'];
                $new_add_obj = populate((Object)((Array)$add_obj), $data);
                if (!$this->MTaskApplyNum->add($new_add_obj)) {
                    $this->db->_trans_status = FALSE;
                }
            }
        } else if ($data['apply_type'] == 'comment') {
            $obj->comment_applied_num += $data['apply_num'];
            if ($obj->comment_applied_num > $obj->comment_need_num) {
                exit(json_encode([
                    'success' => 0,
                    'msg' => '超出最大可接测评数目，请刷新后重试'
                ]));
            }
            if ($his) {
                $his->apply_comment_num += $data['apply_num'];
                if (!$this->MTaskApplyNum->update($his)) {
                    $this->db->_trans_status = FALSE;
                }
            } else {
                $add_obj = $this->MTaskApplyNum->createVo();
                $add_obj->apply_comment_num = $data['apply_num'];
                $new_add_obj = populate((Object)((Array)$add_obj), $data);
                if (!$this->MTaskApplyNum->add($new_add_obj)) {
                    $this->db->_trans_status = FALSE;
                }
            }
        }

        $newObj = populate((Object)((Array)$obj), $data);
        if (!$this->MTask->update($newObj)) {
            $this->db->_trans_status = FALSE;
        }

        $this->db->trans_complete();
        if ($this->db->trans_status() !== FALSE) {
            exit(json_encode([
                'success' => 1,
                'msg' => '操作成功'
            ]));
        } else {
            exit(json_encode([
                'success' => 0,
                'msg' => '操作失败'
            ]));
        }
    }

    function ajaxViewRecordNum($task_id){

        if (!$task = $this->MTask->getById((int)$task_id)) {
            model_error('当前任务不存在！');
        }
        $this->load->model('MTaskApplyNum');
        $taskApplyNumList = $this->MTaskApplyNum->getAll(array('task_id'=>$task_id));
        $allResults = $this->MAdmin->getAll();
        $allAdmins = array();
        foreach ($allResults as $k=>$v){
            $allAdmins[$v->id] = $v->account.'-'.$v->name;
        }
        $this->assign('task', $task);
        $this->assign('allAdmins', $allAdmins);
        $this->assign('taskApplyNumList', $taskApplyNumList);
        $this->assign('thisControllerName', '查看接单及完成数量');
        $this->layout_modal('modal-record-num');
    }
}
